{
 "nbformat": 4,
 "nbformat_minor": 2,
 "metadata": {
  "language_info": {
   "name": "python",
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   }
  },
  "orig_nbformat": 2,
  "file_extension": ".py",
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "version": 3
 },
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "from collections import deque, defaultdict\n",
    "\n",
    "class Solution:\n",
    "    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n",
    "        if endWord not in wordList:\n",
    "            return 0\n",
    "        L = len(beginWord)\n",
    "        all_combo_dict = defaultdict(list)\n",
    "        for word in wordList:\n",
    "            for i in range(L):\n",
    "                all_combo_dict[word[:i] + \"*\" + word[i+1:]].append(word)\n",
    "        \n",
    "        d = deque()\n",
    "        d.append((beginWord, 1))\n",
    "        visited = {}\n",
    "        while d:\n",
    "            word1, step = d.pop()\n",
    "\n",
    "            for i in range(L):\n",
    "                combo_word = word1[:i] + \"*\" + word1[i+1:]\n",
    "                words = all_combo_dict.get(combo_word, [])\n",
    "                for word in words:\n",
    "                    if word1 == endWord:\n",
    "                        return step\n",
    "                    if word not in visited:\n",
    "                        d.appendleft((word, step+1))\n",
    "                        visited[word] = True\n",
    "\n",
    "        else: # 这点没考虑到，需要返回0\n",
    "            return 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自己写的查找字符串的方法超时了，还是看的官方的题解"
   ]
  }
 ]
}